<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Student;
use App\Models\VideoPay;
use App\Repositories\CompositeRepository;
use App\Repositories\OssRepository;
use App\Repositories\PracticeRepository;
use App\Repositories\VideoRepository;
use App\Repositories\VideoLearnRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Models\Composite;
use App\Models\Video;
use App\Models\VideoLearn;

class PracticeController extends BaseController
{

    protected $pracitce;
    protected $composite;
    protected $video;
    protected $video_learn;
    protected $oss;

    public function __construct(
        PracticeRepository $practice,
        CompositeRepository $composite,
        VideoRepository $video,
        VideoLearnRepository $video_learn,
        OssRepository $oss
    )
    {
        $this->practice = $practice;
        $this->composite = $composite;
        $this->video = $video;
        $this->video_learn = $video_learn;
        $this->oss = $oss;
    }

    /**
     * @api {get} /practice/detail 理论练习题目详情
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/detail
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [id=1]  传入题目的ID
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *          "id": 1599,
                "cloumName": "",
                "title": "考试题目 -----例如 夜间驾驶机动车在窄路、窄桥会车怎样使用灯光？",
                "titleUrl": "",
                "answer": "答案 -----例如：A、关闭所有灯光||B、开启近光灯||C、关闭前照灯||D、开启远光灯",
                "answerT": "正确答案编号 ---- 例如：B，ABC",
                "pid": 1,
                "mid": 5,
                "stauts": "1",
                "type": "1", 1为单选，2为多选，3为判断
                "sid": 1,
                "content": "答案解析 ----《道路交通安全法实施条例》第四十八条：在没有中心隔离设施或者没有中心线的道路上，夜间会车应当在距相对方向来车150米以外改用近光灯，在窄路、窄桥与非机动车会车时应当使用近光灯。",
                "ydt_id": 132
     *
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */

    public function detail(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        if(!$id = $request->get('id')){
            return $this->errorResponse('参数错误');
        }

        $data['question'] = $this->practice->getById($id);

        $data['question']['answer'] = explode('||', $data['question']['answer']);
        $data['question']['titleUrl'] = $data['question']['titleUrl'] ? 'http://www.exc360.com'.$data['question']['titleUrl'] : $data['question']['titleUrl'];

        return $this->successResponse('success',['data'=>$data]);
    }


    /**
     * @api {get} /practice/getChapterList 理论练习题章节列表
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/getChapterList
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [km_id=1]  类型  1为科目一的章节列表 2为科目四的章节列表
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *            "id": 9, //章节ID
     *            "cloumname": "违法行为综合判断与案例分析(科目四)" //章节名称
     *            "total": 23 //本章节所包含的题目数量
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */

    public function chapterList(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param = [
            'km' => $request->get('km_id'),//章节列表的科目类型1,2
        ];

        if(!($param['km'] && in_array($param['km'],[1,2]))){
            return $this->errorResponse('参数错误');
        }

        $data = $this->composite->index($param);

        return $this->successResponse('success',['data'=>$data]);
    }


    /**
     * @api {get} /practice/chapterLearn 理论练习题章节列表题目
     * @apiDescription 理论测试/章节练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/chapterLearn
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [zid=1]  章节ID
     * @apiParam {Number} [page=1] 第几题
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *            "id": 9, //章节ID
     *            "cloumname": "违法行为综合判断与案例分析(科目四)" //章节名称
     *            "total": 23 //本章节所包含的题目数量
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */

    public function chapterLearn(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param = $request->input();

        if(!$param['zid'] || !$param['page']){
            return $this->errorResponse('参数错误');
        }

        $data = $this->practice->index($param);

        return $this->successResponse('success',['data'=>$data]);
    }


    /**
     * @api {get} /practice/addWrong 理论练习题错题添加
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/addWrong
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [type=1]  类型  1：学员 2：教练 3：驾校
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *           "id":'主键',
     *           "name": "名称",
     *           "idcard": "身份证号",
     *
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */

    public function addWrong()
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        return $this->successResponse('success',['data'=>[]]);
    }


    /**
     * @api {get} /practice/delWrong 理论练习题错题记录删除
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/delWrong
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [type=1]  类型  1：学员 2：教练 3：驾校
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *           "id":'主键',
     *           "name": "名称",
     *           "idcard": "身份证号",
     *
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function delWrong()
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        return $this->successResponse('success',['data'=>[]]);
    }


    /**
     * @api {get} /practice/getWrongList 理论练习题错题记录列表
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/getWrongList
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [type=1]  类型  1：学员 2：教练 3：驾校
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *           "id":'主键',
     *           "name": "名称",
     *           "idcard": "身份证号",
     *
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */

    public function getWrongList()
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        return $this->successResponse('success',['data'=>[]]);
    }


    /**
     * @api {get} /practice/theory 理论练习理论视频学习
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/theory
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data":  [
                        {
                        "id": 284,
                        "name": "机动车驾驶证申领与使用",
                        "parentid": 281,
                        "big": 0,
                        "url": "http://cache.jsy360.cn/exc360III/01.mp4",
                        "newurl": "http://cache.jsy360.cn/exc360II/01.mp4",
                        "duration": 1932,
                        "desc": "",
                        "typeid": 1,
                        "status": 1,
                        "listorder": 1,
                        "number": 1,
                        "learned": 1 是否已经学习过，1是，0否
                        },
     *               ]
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function theory(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $where[] = ['status', 1];//状态

        $data = $this->video->index($where, $user->item_id);

        return $this->successResponse('success',['data'=>$data]);
    }


    /**
     * @api {get} /practice/theoryCheck 理论练习理论视频学习权限
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/theoryCheck
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [km]  学习的科目
     * @apiParam {Number} [video_id]  要学习的视频ID
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data":  [
     *               ]
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function theoryCheck(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $data = $this->video->theoryCheck($user->item, $request->input('km'), $request->input('video_id'));

        return $this->successResponse('success',['data'=>$data]);
    }


    /**
     * @api {get} /practice/theoryPayCheck 理论练习理论视频学习是否支付
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/theoryPayCheck
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [video_id]  学习的视频ID
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data":  [
     *               ]
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function theoryPayCheck(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $video_pay = VideoPay::where('student_id', $user->item_id)->where('video_id', $request->input('video_id'))->first();

        if($user->item->video_pay || $user->item->school->free_theory || $video_pay){//后台设置免费
            return $this->successResponse('success',['data'=> ['status' => 1, 'money' => 0]]);
        }

        return $this->successResponse('success',['data'=> ['status' => 0, 'money'=>config('pay.video_money')]]);
    }

    /**
     * @api {post} /practice/theoryRecord 理论练习理论视频学习记录
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/theoryRecord
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [video_id]  学习的视频ID
     * @apiParam {Number} [duration]  学习的视频时长 可选
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *           "name": "机动车驾驶证申领与使用",//视频名称
    "url": "http://cache.jsy360.cn/exc360III/01.mp4",//视频地址
    "newurl": "http://cache.jsy360.cn/exc360II/01.mp4",//视频地址
    "duration": 1932,//视频时长
     *
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public  function theoryRecord(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param = [
            'video_id' => $request->input('video_id'),
            'duration' => $request->input('duration'),
        ];

        if(!$param['video_id']){
            return $this->errorResponse('参数错误');
        }

        $param['student_id'] = $user->item_id;
        $param['school_id'] = Student::find($user->item_id)->school_id;

        $this->video_learn->store($param, '');
        return $this->successResponse('success',['data'=>[]]);
    }

    /**
     * @api {get} /practice/simulate 理论练习理论模拟考试
     * @apiDescription 理论测试/练习
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/simulate
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [km=1]  1为科目一考试 2为科目四考试
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *           "id": [1,2,3,4,5]
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function simulate(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token


        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param = [
            'km' => $request->get('km'),//模拟测试的科目类型1,2
        ];

        if(!($param['km'] && in_array($param['km'],[1,2]))){
            return $this->errorResponse('参数错误');
        }

        $data = $this->practice->getSimulate($param['km']);


        return $this->successResponse('success',['data'=>$data]);
    }


    /**
     * @api {post} /practice/theoryPhoto 理论练习拍照
     * @apiDescription 理论测试/拍照
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/theoryPhoto
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {video_id} [video_id]  视频id
     * @apiParam {image} [image]  base64编码的图片内容
     * @apiParam {type} [type]  1表示看前拍照，2表示看完拍照
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *           "id": [1,2,3,4,5]
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function theoryPhoto(Request $request)
    {

        $user = JWTAuth::parseToken()->authenticate();//验证token


        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $image = $request->input('image');
        $video_id = $request->input('video_id');
        $type = $request->input('type');

        if($image){
            $file_name = 'theory_photo/'.$user->item->id.'_'.$video_id.'_'.$type.'.jpg';
            $rs = $this->oss->uploadContentToFile(base64_decode($image), $file_name);

            if($rs['state']){
                return $this->successResponse('上传成功', ['data'=>[]]);
            }
        }

        return $this->errorResponse('上传失败',['data' => '']);

    }


    /**
     * @api {get} /practice/learnRandom 理论练习题章节随机
     * @apiDescription 理论练习题章节随机
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/learnRandom
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [page=1] 第几题
     * @apiParam {Number} [km] 科目
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *            "id": 9, //章节ID
     *            "cloumname": "违法行为综合判断与案例分析(科目四)" //章节名称
     *            "total": 23 //本章节所包含的题目数量
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function learnRandom(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param = $request->input();

        if(!$param['page']){
            return $this->errorResponse('参数错误');
        }

        $data = $this->practice->learnList($param, 2);

        return $this->successResponse('success',['data'=>$data]);
    }



    /**
     * @api {get} /practice/learnOrder 理论练习题章节顺序
     * @apiDescription 理论练习题章节顺序
     * @apiGroup pratice
     * @apiPermission none
     * @apiSampleRequest /api/practice/learnOrder
     * @apiHeader {String} Authorization 用户旧的jwt-token, value已Bearer开头
     * @apiParam {Number} [page=1] 第几题
     * @apiParam {Number} [km] 科目
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": {
     *            "id": 9, //章节ID
     *            "cloumname": "违法行为综合判断与案例分析(科目四)" //章节名称
     *            "total": 23 //本章节所包含的题目数量
     *       }
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function learnOrder(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $param = $request->input();

        if(!$param['page']){
            return $this->errorResponse('参数错误');
        }

        $data = $this->practice->learnList($param, 1);

        return $this->successResponse('success',['data'=>$data]);
    }
}